#! /usr/bin/python3
import os
import time
import abc
import serial
from tools import Tools


class IVPTest:
    def __init__(self, com, ctime, path, name):
        self.com = com
        self.path = path
        self.ctime = ctime
        self.name = name

    @abc.abstractmethod
    def test(self):
        return

    def log_dir(self):
        return self.ctime + '/' + self.name

    def dir_list(self):
        file_list = []
        lists = os.listdir(self.path)
        for i in range(0, len(lists)):
            file = self.path + '/' + lists[i]
            if os.path.isfile(file):
                file_list.append(file)
        return file_list

    def get_file(self, file):
        if self.path[-1] == '/':
            return self.path + file
        return self.path + '/' + file

    def run(self, file, log_file):
        # flog = open(log_file, 'ab+')
        # ser = serial.Serial(self.__com, 115200, timeout=5)
        # if ser.open():
        #     print("Open %s success!" % com)
        # else:
        #     print("Open %s failed!" % com)
        #     return 1
        self.ivp_cmd(file)
        # result = ser.readlines()
        # for context in result:
        #     flog.write()
        # ser.close()
        # flog.close()
        return 0

    @staticmethod
    def ivp_cmd(file):
        func = file.split('/')
        print("%s test start!" % func[-1])
        print("file is %s!" % file)
        filep = open(file, 'r', encoding='utf-8', errors='ignore')
        while True:
            context = filep.readline()
            if not context:
                break
            if context.startswith(('::', 'rem', 'REM')):
                continue
            if context.count('pause'):
                time.sleep(3)
                continue
            if context.count('ping'):
                value = context.split(' ')
                if value[2].isdigit():
                    time.sleep(int(value[2]))
                continue
            if context.count('bin'):
                context = context.replace('testcore.bin', '%s/testcore.bin' % file[:file.rfind('/')])
            print("command is %s" % context)
            # os.system(context)
        filep.close()
        return 0

    @staticmethod
    def create_dir(path):
        os.makedirs(path, 777, True)
        return 0

    @staticmethod
    def get_log(directory, file):
        if directory[-1] == '/':
            return directory + file
        return directory + '/' + file


class Idma(IVPTest):
    def __init__(self, com, ctime, path='./dma', name='dma'):
        super().__init__(com, ctime, path, name)

    def test(self):
        if not os.path.exists(self.path):
            print("self path is {}".format(self.path))
            print("Bat path is not exist!")
            return False
        file_list = self.dir_list()
        for file in file_list:
            index = file.rfind(".")
            if index == -1 or file[index + 1] == '/':
                continue
            extension = file[index + 1:]
            if extension == 'bat':
                log_file = file.replace(self.path, self.log_dir())
                log_file = log_file.replace('bat', 'txt')
                if not os.path.exists(log_file):
                    self.create_dir(log_file[:log_file.rfind('/')])
                self.run(file, log_file)
        return True


if __name__ == '__main__':
    os.chdir('./')
    curtime = Tools.cur_time()
    dma = Idma('com3', curtime)
    dma.test()
    print("test end!")
